import React, { useEffect, useState } from 'react';
import { Space, Table, Tag, Form, Input, Checkbox, Button, Modal, Popconfirm } from 'antd';
import type { TableProps } from 'antd';
import http from '../../api/http';
import type { FormProps } from 'antd';

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
function Index() {
  //定义表格
  const [data, setData] = useState([])
  //总页数
  const [total, setTotal] = useState(0)
  //当前页
  const [page, setPage] = useState(1)
  //每页个数
  const [pageSize, setPageSise] = useState(10)
  //搜索form
  const [form] = Form.useForm()
  //弹框forms
  const [forms] = Form.useForm()
  //定义搜索
  const [title, setTitle] = useState('')
  const [tag, setTag] = useState('')

  const getlist = async () => {
    const params: {
      page: number,//页码
      pageSize: number,//每页显示条数
      keyword: string,//搜索标题
      tag?: string,//搜索标签
    } = {
      page, pageSize
    }
    if (title) params.keyword = title
    if (tag) params.tag = tag
    const res = await http.get('/article/list', { params })
    console.log(res);
    setData(res.data.rows)
    setTotal(res.data.count)
  }
  //分页
  const change = (page: number, pageSize: number) => {
    setPage(page)
    setPageSise(pageSize)
  }
  //搜索
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    setTitle(values.title)
    setTag(values.tag)
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  //新增与编辑
  const [open, setOpen] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [flag, setFlag] = useState(true)
  const showModal = (row) => {
    setOpen(true)
    setFlag(false)
    forms.setFieldsValue(row)
  };

  const handleOk = async () => {
    setFlag(true);
    const { id, title, content } = forms.getFieldsValue()
    if (flag) {
      const res = await http.post('/article', {
        title,//文章标题
        content,//文章内容
        tagList: ["HTTP"],//标签  array[string]
        categoryList: ["HTTP"],//分类  array[string]
        authorId: 47529555//用户id 暂时写死47529555 登陆成功后返回的用
      })
      console.log(res)
      setOpen(false)
      getlist()
      forms.resetFields()
    } else {
      const res = await http.put(`/article/${id}`, {
        title,//文章标题
        content,//文章内容
        tagList: ["HTTP"],//标签  array[string]
        categoryList: ["HTTP"],//分类  array[string]
        authorId: 47529555//用户id 暂时写死47529555 登陆成功后返回的用
      })
      console.log(res)
      setOpen(false)
      getlist()
      forms.resetFields()
    }
    setConfirmLoading(false)
  };

  const handleCancel = () => {
    setOpen(false);
  };
  useEffect(() => {
    getlist()
  }, [page, pageSize, title, tag])
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '文章内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '阅读数量',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => showModal(record)}>编辑</Button>
          <Button onClick={() => showModal(record)}>查看</Button>
          <Popconfirm
            title="删除"
            description="你确定要删除吗?"
            onConfirm={() => confirm.id}

            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // const data: DataType[] = [
  //   {
  //     key: '1',
  //     name: 'John Brown',
  //     age: 32,
  //     address: 'New York No. 1 Lake Park',
  //     tags: ['nice', 'developer'],
  //   },
  //   {
  //     key: '2',
  //     name: 'Jim Green',
  //     age: 42,
  //     address: 'London No. 1 Lake Park',
  //     tags: ['loser'],
  //   },
  //   {
  //     key: '3',
  //     name: 'Joe Black',
  //     age: 32,
  //     address: 'Sydney No. 1 Lake Park',
  //     tags: ['cool', 'teacher'],
  //   },
  // ];

  return (
    <div>
      <Form
        name="basic"
        form={form}
        layout='inline'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 800 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="标题"
          name="title"

        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="标签"
          name="tag"

        >
          <Input />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            重置
          </Button>
        </Form.Item>

      </Form>
      <Button type="primary" onClick={() => setOpen(true)}>新增+</Button>
      <Modal
        title={flag ? '新增' : '编辑'}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={forms}

          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 800 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          confirmLoading={confirmLoading}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="id"
            name="id"

          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="文章标题"
            name="title"

          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="文章内容"
            name="content"

          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <Table<DataType> columns={columns} dataSource={data}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: change
        }}
      />
    </div>
  )
}

export default Index
